package cn.lcfms.app.admin.controller;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.coobird.thumbnailator.Thumbnails;
import net.sf.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import cn.lcfms.app.admin.service.CommonService;
import cn.lcfms.bin.BaseCache;
import cn.lcfms.bin.core.Application;
import cn.lcfms.bin.service.BaseService;
import cn.lcfms.utils.CommonUtils;
import cn.lcfms.utils.TimeUtils;
import cn.lcfms.utils.TimeUtils.Formatter;


@Controller("admin.CommonController")
@RequestMapping("/admin/common")
public class CommonController extends AdminBaseController{
	
	@Autowired
	private CommonService cs;
	
	
	@RequestMapping("/login")
	public String login(HttpServletRequest request){
		String basePath=(String) request.getAttribute("APP");
    	request.setAttribute("JS", basePath+"statics/ace/js/"); 
    	request.setAttribute("CSS", basePath+"statics/ace/css/"); 
    	request.setAttribute("IMG", basePath+"statics/ace/images/"); 
    	request.setAttribute("formUuid", BaseCache.getFormUuid(60*10)); 
    	return "admin/login";
	}
	
	@RequestMapping("/areas")
	public String areas(int id){
		BaseService service=Application.getService("areas");
		service.where("parent_id="+id);
		service.column("id","name");
		List<HashMap<String, Object>> list = service.selectList();
		JSONArray array=JSONArray.fromObject(list);
		return array.toString();
	}
	
	@RequestMapping("/mobileVerifyCode")
	public String getVerifyCode(String formUuid,String mobile) {
		if(!BaseCache.VerifyFormUuid(formUuid)) {
			return "{code:0,msg:发送失败，表单已经过期，请刷新页面！}";
		}
		String randomNum = CommonUtils.getRandomNum(4);
		System.out.println(randomNum);
		String msg_content = "您的验证码是：" + randomNum + "。请不要把验证码泄露给其他人。如非本人操作，可不用理会！";
		try {
			boolean bool=BaseCache.putFormCache(formUuid+":mobile",randomNum);
			if(!bool) {
				return "{code:0,msg:发送失败，表单已经过期，请刷新页面！}";
			}
			cs.sendMsg(msg_content,mobile);		
			return "{code:1,msg:发送成功！}";
		} catch (Exception e) {
			return "{code:0,msg:"+e.getMessage()+"}";			
		}						
	}
	
	@RequestMapping("/imgVerifyCode")
	public void imgVerifyCode(HttpServletResponse response,@RequestParam(required=true)String formUuid) throws IOException {
		response.setContentType("image/jpeg");// 设置相应类型,告诉浏览器输出的内容为图片
		response.setHeader("Pragma", "No-cache");// 设置响应头信息，告诉浏览器不要缓存此内容
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expire", 0);
		String randomStr;
		if(!BaseCache.VerifyFormUuid(formUuid)) {
			randomStr="u pig";
		}else {
			randomStr= CommonUtils.getRandomStr(4);
			BaseCache.putFormCache(formUuid+":img",randomStr);	
		}	
		BufferedImage image = CommonUtils.imgRandcode(randomStr);
		try {
			ImageIO.write(image, "JPEG", response.getOutputStream());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	@RequestMapping("/fileupload")
	public String fileupload(String dir,@RequestParam("uploadFileName") MultipartFile file,HttpServletRequest request) throws IOException{		
		int size = (int) Application.config("maxfilesize");
		if(file.getSize()>0 && file.getSize()<(size*1024*1024)){
			String filefullname=file.getOriginalFilename();	
			int index=filefullname.lastIndexOf(".");
			//文件老名字
			String alt="";
			//文件类型
			String filetype="";
			//文件新名字
			String filename="";
			//扩展名
			String extension="";
			SimpleDateFormat sdf=new SimpleDateFormat("yyyyMM");
			Date date = new Date();
			//日期文件夹
			String fold=sdf.format(date);
			String s=File.separator;
			//存储的文件夹
			String path="";
			if(index!=-1){
				alt=filefullname.substring(0, index);
				extension=filefullname.substring(index).toLowerCase();
			}else{
				alt=filefullname;
			}
			String fts = (String) Application.config("filetype");
			String[] split = fts.split(",");
			boolean b=true;
			for(String ft:split) {
				if(("."+ft).equals(extension)) {
					b=false;
					break;
				}
			}
			if(b) {
				return "{error:1,message:文件格式不支持上传！}";
			}
			if(extension.equals(".png") || 
			   extension.equals(".jpg") || 
			   extension.equals(".jpeg")||
			   extension.equals(".bmp") ||
			   extension.equals(".gif")
			  ){
				path=Application.ROOT_PATH+s+"uploadfile"+s+"images"+s+fold+s;
				filetype="img";
			}else if(extension.equals(".mp3")){
				path=Application.ROOT_PATH+s+"uploadfile"+s+"music"+s+fold+s;
				filetype="music";
			}else if(extension.equals(".mp4")){
				path=Application.ROOT_PATH+s+"uploadfile"+s+"video"+s+fold+s;
				filetype="video";
			}else {
				path=Application.ROOT_PATH+s+"uploadfile"+s+"file"+s+fold+s;
				filetype="file";
			}
			Random r=new Random();
			String ri = String.valueOf(r.nextInt(1000));
			filename=String.valueOf(date.getTime()).substring(3,13)+ri+extension;
			File f=new File(path+filename);
			File fo=new File(path);		
			if(!fo.exists()){
				fo.mkdirs();
			}		
			f.createNewFile();
			file.transferTo(f);
			if(filetype.equals("img")){	
				File fs=new File(path+"thumb");
				if(!fs.exists()){
					fs.mkdirs();
				}
			}		
			long id=fileInsertSql(filetype,filename,alt,fold);			
			if(filetype.equals("img")){			
				String u= "{\"error\":0,\"url\":\""+(String)request.getAttribute("APP")+"uploadfile/images/"+fold+"/"+filename+"\",\"id\":"+id+"}";				
				return u;
			}else if(filetype.equals("music")){
				String u= "{\"error\":0,\"url\":\""+(String)request.getAttribute("APP")+"uploadfile/music/"+fold+"/"+filename+"\",\"id\":"+id+"}";				
				return u;
			}else if(filetype.equals("video")){
				String u= "{\"error\":0,\"url\":\""+(String)request.getAttribute("APP")+"uploadfile/video/"+fold+"/"+filename+"\",\"id\":"+id+"}";				
				return u;
			}else if(filetype.equals("file")){
				String u= "{\"error\":0,\"url\":\""+(String)request.getAttribute("APP")+"uploadfile/file/"+fold+"/"+filename+"\",\"id\":"+id+"}";				
				return u;
			}
		}
		return "{error:1,message:文件大小为0或者文件太大！}";
	}
	
	/**
	 * 
	 * @param filetype 文件类型
	 * @param filename alt名称,非文件名
	 * @param filepath http路径
	 * @param filerealpath 物理路径
	 */
	private long fileInsertSql(String filetype,String filename,String alt,String fold){
		String s=File.separator;
		int r=0;
		BaseService service=Application.getService("files");
		switch (filetype) {
		case "img":			
			String thumbpath=Application.ROOT_PATH+s+"uploadfile"+s+"images"+s+fold+s+"thumb"+s+filename;
			String thumbhttp=fold+"/thumb/"+filename;
			String photopath=Application.ROOT_PATH+s+"uploadfile"+s+"images"+s+fold+s+filename;
			String photohttp=fold+"/"+filename;
			boolean b = operateByMaxSize(photopath,thumbpath);
			if(!b){
				thumbhttp=photohttp;
			}
			service.setData("img",alt,photohttp,thumbhttp,TimeUtils.getCurrentDateTime(Formatter.SHORT));
			service.insert("type","name","original","thumbnail","created_at");	
			r=service.insert_id();
			break;
		case "music":	
			String musicpath=fold+"/"+filename;
			service.setData("music",alt,musicpath,TimeUtils.getCurrentDateTime(Formatter.SHORT));
			service.insert("type","name","original","created_at");	
			r=service.insert_id();
			break;
		case "video":
			String videopath=fold+"/"+filename;
			service.setData("video",alt,videopath,TimeUtils.getCurrentDateTime(Formatter.SHORT));
			service.insert("type","name","original","created_at");	
			r=service.insert_id();
			break;
		case "file":
			String filepath=fold+"/"+filename;
			service.setData("file",alt,filepath,TimeUtils.getCurrentDateTime(Formatter.SHORT));
			service.insert("type","name","original","created_at");	
			r=service.insert_id();
			break;
		default:
			break;
		}
		return r;
	}
	//保持宽度250px不变,等比例压缩图片
	private boolean operateByMaxSize(String inSrc,String outSrc){  
        boolean flag = false;  
        try {  
        	BufferedImage bi = ImageIO.read(new File(inSrc));
        	int m=(250*bi.getHeight())/bi.getWidth();        	   	
        	Thumbnails.of(bi).size(250, m).toFile(outSrc);
            flag = true;  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
        return flag;  
    }  
	
	public static void main(String[] args) {
		long l=39l;
		System.out.println(l>5*1024*1024);
	}
}
